package com.fau.wmbj.server.controller;

import cn.dev33.satoken.secure.BCrypt;
import com.fau.wmbj.server.config.CurrentUser;
import com.fau.wmbj.server.entity.Role;
import com.fau.wmbj.server.entity.User;
import com.fau.wmbj.server.service.RoleService;
import com.fau.wmbj.server.service.UserService;
import com.fau.wmbj.server.utils.Filter;
import com.fau.wmbj.server.utils.Message;
import com.fau.wmbj.server.utils.Page;
import com.fau.wmbj.server.utils.Pageable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 用户管理
 *
 * @author jiawei
 * @version 1.0
 * @datetime 2024-02-28 14:06
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;

    @RequestMapping("/getUserList")
    @ResponseBody
    public Message getUserList(@RequestBody Pageable pageable, @CurrentUser User user) {
        List<Filter> filters = pageable.getFilters();
        filters.add(Filter.eq("role.company", user.getRole().getCompany()));
        Page<User> page = userService.findPage(pageable);
        return Message.success(page);
    }

    @RequestMapping("/getUserInfo")
    @ResponseBody
    public Message getUserInfo(@RequestBody User user) {
        List<Filter> filters = user.getFilters();
        return Message.success(userService.findEntity(filters));
    }

    @RequestMapping("/save")
    @ResponseBody
    public Message save(@RequestBody User user2) {
        Map<String, Object> params = user2.getParams();
        Integer roleId = (Integer) params.get("roleId");
        Role role = roleService.find(Long.valueOf(roleId));
        user2.setEnabled(true);
        String pw_hash = BCrypt.hashpw(user2.getPassword(), BCrypt.gensalt());
        user2.setEncryptedPassword(pw_hash);
        user2.setRole(role);
        userService.save(user2);
        return Message.success();
    }
}
